import { useState, useEffect, useRef } from 'react';

const useCountdown = (initialCount, callBack = () => { }) => {
    const [count, setCount] = useState(null);
    const timer = useRef()

    const init = () => {
        clearInterval(timer.current);
        timer.current = setInterval(() => {
            setCount((prevCount) => {

                if (prevCount === 1) {
                    callBack();
                }
                if (prevCount === 0) {
                    // setCount(null)
                    clearInterval(timer.current);
                    return prevCount
                }
                return prevCount - 1
            });
        }, 1000);
    }

    useEffect(() => {
        return () => {
            clearInterval(timer.current);
        };
    }, []);

    const resetCountdown = () => {
        setCount(initialCount);
        init()
    };

    return { count, resetCountdown };
};

export default useCountdown;